
export function getUserInfo() {
	let userInfo = uni.getStorageSync("UserInfo") ?? {};
	if (!userInfo) userInfo = {};
	return userInfo;

}

export function setUserNickName(nickname) {
	let userInfo = getUserInfo() ?? {};
	if (!userInfo) userInfo = {};
	userInfo.nickname = nickname;
	uni.setStorageSync("UserInfo", userInfo);
	return userInfo;
}


export function setUserAvatar(avatar) {
	let userInfo = getUserInfo() ?? {};
	if (!userInfo) userInfo = {};
	console.log("userInfo:" + userInfo);
	userInfo.avatar = avatar;
	uni.setStorageSync("UserInfo", userInfo);
	return userInfo;
}

export function setUserInfo(userInfo) {
	uni.setStorageSync("UserInfo", userInfo);
	return userInfo;
}


export function saveUserCloudScore(score) {
	uni.setStorageSync("CloudScore", score);
	return getTotalUserScore();
}

export function saveUserAddScore(score) {
	const current = uni.getStorageSync('AddScore');
	const currentScore = Number(current);
	let sum = 0;
	if (currentScore && currentScore != 0) {
		sum = score + currentScore;
		uni.setStorageSync("AddScore", sum);
	} else {
		sum = score;
		uni.setStorageSync("AddScore", score);
	}
	return getTotalUserScore();
}

export function getTotalUserScore() {
	const current = uni.getStorageSync('AddScore');
	const currentCloud = uni.getStorageSync('CloudScore');
	const currentScore = Number(current);
	const currentCloudScore = Number(currentCloud);
	if (currentScore && currentCloudScore) {
		return currentScore + currentCloudScore;
	} else {
		if (currentScore) {
			return currentScore;
		} else if (currentCloudScore) {
			return currentCloudScore;
		}
		return 0;
	}
}

export function saveUserTotalScore() {
	const db = uniCloud.database();
	// 获取全部分数
	const current = uni.getStorageSync('AddScore');
	const openid = uni.getStorageSync("UserOpenId");
	const currentScore = Number(current);
	const query = db.collection("uni-id-users").where({
		username: openid.toLowerCase()
	});
	query.field('score as score').get().then(res => {
		if (res.result.data && res.result.data.length) {
			const total = res.result.data[0].score + currentScore;
			console.log("saveUserTotalScore",total+JSON.stringify(res.result.data));
			query.update({
				score: total
			}).then(res2 => {
				uni.setStorageSync("AddScore", 0);
				saveUserCloudScore(total);
			})
		}
	});
}